<?php

namespace app\controller\admin\fire;

use app\model\api\fire\FireAuthor;
use app\model\api\fire\FireRecord;
use laytp\controller\Backend;

/**
 * Class Author
 * @package app\controller\admin\peace
 */
class Author extends Backend
{
    /**
     * api_log模型对象
     * @var \app\model\api\Log
     */
    protected $model;
    protected $hasSoftDel=0;//是否拥有软删除功能

    protected $noNeedLogin = []; // 无需登录即可请求的方法
    protected $noNeedAuth = ['index', 'info']; // 无需鉴权即可请求的方法

    public $orderRule = ['sort' => 'desc', 'id' => 'asc'];

    public function _initialize()
    {
        $this->model = new FireAuthor();
    }

    /**
     * 作者
     * @return false|string|\think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function author(){
        $where = $this->buildSearchParams();

        $all_author_ids = (new FireRecord())->where($where)->column('author_id');
        $all_author_ids = array_values(array_unique($all_author_ids));

        $author_id = $this->request->param('author_id');
        if($author_id && in_array($author_id,$all_author_ids)){
            $index = array_search($author_id,$all_author_ids);
            unset($all_author_ids[$index]);
        }
        $data = $this->model
            ->where(array(['id', 'not in', implode(',',$all_author_ids)]))
            ->select()->toArray();

        return $this->success('数据获取成功', $data);
    }

    //设置排序
    public function setSort()
    {
        $id       = $this->request->post('id');
        $fieldVal = $this->request->post('field_val');
        $isRecycle = $this->request->post('is_recycle');
        $update['author_sort'] = $fieldVal;

        try {
            if($isRecycle) {
                $this->model->onlyTrashed()->where('id', '=', $id)->update(array('sort' => $fieldVal));
                $updateRes = (new FireRecord())->onlyTrashed()->where('author_id', '=', $id)->update($update);
            } else {
                $this->model->where('id', '=', $id)->update(array('sort' => $fieldVal));
                $updateRes = (new FireRecord())->where('author_id', '=', $id)->update($update);
            }

            if ($updateRes) {
                $this->clearCache();
                return $this->success('操作成功');
            } else if ($updateRes === 0) {
                return $this->success('未作修改');
            } else {
                return $this->error('操作失败');
            }
        } catch (\Exception $e) {
            return $this->exceptionError($e);
        }
    }

}